//定位,must为true是不管有无，必须定位
function locating(must) {
    //获取坐标
    var hasLocXY = getCookie("qyll");
    if(hasLocXY && !must){
        return;
    }
    //没有经纬度进行定位
    var map, geolocation;
    // 加载地图，调用浏览器定位服务
    map = new AMap.Map('container', {
        resizeEnable : true
    });
    map.plugin('AMap.Geolocation', function() {
        geolocation = new AMap.Geolocation({
            enableHighAccuracy : true,// 是否使用高精度定位，默认:true
            timeout : 1000, // 超过10秒后停止定位，默认：无穷大
            buttonOffset : new AMap.Pixel(10, 20),// 定位按钮与设置的停靠位置的偏移量，默认：Pixel(10,20)
            zoomToAccuracy : true, // 定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            buttonPosition : 'RB'
        });
        map.addControl(geolocation);
        geolocation.getCurrentPosition();
        AMap.event.addListener(geolocation, 'complete', onComplete);// 返回定位信息
        AMap.event.addListener(geolocation, 'error', onError);// 返回定位信息
    });
}

// 解析定位结果失败
function onError(data) {
    alert("定位失败");
    console.log("定位失败");
}

// 解析定位结果成功
function onComplete(data) {
    alert("定位成功");
    var locXYStr = data.position.getLat() + "-" + data.position.getLng();
    //设置经纬度到cookie
    setCookie("qyll",locXYStr);
    var lnglatXY = [Number(data.position.getLng()),Number(data.position.getLat())];
    regeocoder(lnglatXY)
}

//逆地理编码
function regeocoder(lnglatXY) {
    var geocoder = new AMap.Geocoder({
        radius: 1000,
        extensions: "all"
    });
    geocoder.getAddress(lnglatXY, function(status, result) {
        var cityCode = result.regeocode.addressComponent.citycode;
        var cityName = result.regeocode.addressComponent.city;
        if(rf){
            rf(cityCode,cityName);
        }else{
            var areaCode = getCookie("qyac");
            if(areaCode == null || areaCode == "" || (cityCode != areaCode)){
                setCookie("qyac",cityCode);
                window.location.reload();
            }else if(cityCode != areaCode){
                layer.confirm('是否切换到' + cityName + '？', {
                    btn: ['是','否'] //按钮
                }, function(){
                    setCookie("qyac",cityCode);
                    window.location.reload();
                }, function(){
                    //其他页面不在询问
                });
            }
        }
    });
}
